//
//  LCCycleScrollView.m
//  LCCycleScrollView
//
//  Created by admin on 2017/8/17.
//  Copyright © 2017年 LC. All rights reserved.
//

#import "LCCycleScrollView.h"
#import "Masonry/Masonry.h"
#import <SDWebImage/UIImageView+WebCache.h>

@interface LCCycleCollectionViewCell : UICollectionViewCell

@property (strong, nonatomic)   UILabel     *cycleLabel;

@end

@implementation LCCycleCollectionViewCell

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _cycleLabel = [UILabel new];
        _cycleLabel.textAlignment = NSTextAlignmentCenter;
        [_cycleLabel sizeToFit];
        
        [self.contentView addSubview:_cycleLabel];
    
        [_cycleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.contentView);
        }];
        
    }
    return self;
}

@end

@interface LCCycleScrollView () <UICollectionViewDataSource,UICollectionViewDelegate,UIScrollViewDelegate>

@property (strong, nonatomic)   UICollectionView    *cycleCollectionView;

@property (strong, nonatomic)   UIPageControl       *pageControl;

@end


@implementation LCCycleScrollView{
    NSInteger   _count;

    NSTimer     *_timer;
}

#pragma mark - 重写属性 -
- (void)removeFromSuperview {
    [self clearTimer];
}

- (UIPageControl *)pageControl {
    if(_pageControl == nil) {
        _pageControl = [UIPageControl new];
        _pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
        _pageControl.pageIndicatorTintColor = [UIColor clearColor];//设置为透明
        _pageControl.enabled = NO;
        _pageControl.currentPageIndicatorTintColor = [UIColor clearColor];//设置为透明
        [self addSubview:_pageControl];
        [_pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self);
            make.height.mas_equalTo(20);
        }];
    }
    return _pageControl;
}

- (UICollectionView *)cycleCollectionView {
    if(_cycleCollectionView == nil) {
        UICollectionViewFlowLayout *layout = [UICollectionViewFlowLayout new];
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;//水平滑动
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        layout.headerReferenceSize = CGSizeZero;
        layout.footerReferenceSize = CGSizeZero;
        _cycleCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _cycleCollectionView.pagingEnabled = YES;
        _cycleCollectionView.showsVerticalScrollIndicator = NO;
        _cycleCollectionView.showsHorizontalScrollIndicator = NO;
        _cycleCollectionView.backgroundColor = [UIColor clearColor];
        [_cycleCollectionView registerClass:[LCCycleCollectionViewCell class] forCellWithReuseIdentifier:@"CELL"];
        
        
        _cycleCollectionView.dataSource = self;
        _cycleCollectionView.delegate = self;
        
        
        [self addSubview:_cycleCollectionView];
        [_cycleCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self);
        }];
    }
    return _cycleCollectionView;
}

#pragma mark - 轮播器定时器 -


/**
 定时执行的任务
 */
- (void)doTimer {
    CGPoint offset = CGPointMake(self.cycleCollectionView.contentOffset.x + self.cycleCollectionView.frame.size.width, self.cycleCollectionView.contentOffset.y);
    if(offset.x >= self.cycleCollectionView.contentSize.width - self.cycleCollectionView.frame.size.width) {
        offset.x = 0;
    }
    
    
    [self.cycleCollectionView setContentOffset:offset animated:YES];
}

/**
 清空图片轮播
 */
- (void)clearTimer {
    if(_timer != nil) {
        if([_timer isValid]) {
            [_timer invalidate];
        }
        _timer = nil;
    }
}

/**
 开始轮播
 */
- (void)startTimer {
    [self clearTimer];
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(doTimer) userInfo:nil repeats:YES];
}

#pragma mark - 数据源获取数据方法 -
- (NSInteger)numberOfItems {
    NSInteger count = 0;
    
    if(self.dataSource && [self.dataSource respondsToSelector:@selector(numberOfItemsInCycleScrollView:)]) {
        count = [self.dataSource numberOfItemsInCycleScrollView:self];
    }
    return count;
}
#pragma mark - 公开方法 -
/**
 刷新数据
 */
- (void)reloadData {
    [self.cycleCollectionView reloadData];
    _count = [self numberOfItems];
    
//    if(self.delegate && [self.delegate respondsToSelector:@selector(colorForCurrentPageControlInCycleScrollView:)]) {
//        self.pageControl.currentPageIndicatorTintColor = [self.delegate colorForCurrentPageControlInCycleScrollView:self];
//    }
    
    self.pageControl.numberOfPages = _count;
    self.pageControl.currentPage = 0;
    
    [self layoutIfNeeded];
    self.cycleCollectionView.contentOffset = CGPointMake(500 * _count * self.cycleCollectionView.frame.size.width, 0);
    
    [self startTimer];
}

#pragma mark - UICollectionViewDataSource -
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _count * 1000;
}

- (__kindof LCCycleCollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    NSInteger idx = indexPath.row % _count;
    
    
    LCCycleCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CELL" forIndexPath:indexPath];
    
    NSString *url = nil;
    if(self.dataSource && [self.dataSource respondsToSelector:@selector(cycleScrollView:imageURLForItemAtIndex:)]) {
        url = [self.dataSource cycleScrollView:self imageURLForItemAtIndex:idx];
    }
    
    if(url != nil) {
        cell.cycleLabel.text = (NSString *)url;
        
    }
    
    
    
    return cell;
}

//#pragma mark - UICollectionViewDelegate -
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.delegate respondsToSelector:@selector(cycleScrollView:didSelectItemAtIndex:)]) {
        [self.delegate cycleScrollView:self didSelectItemAtIndex:[self pageControlIndexWithCurrentCellIndex:indexPath.item]];
    }
    if (self.clickItemOperationBlock) {
        self.clickItemOperationBlock([self pageControlIndexWithCurrentCellIndex:indexPath.item]);
    }
}
- (int)pageControlIndexWithCurrentCellIndex:(NSInteger)index
{
    return (int)index % _count;
}
#pragma mark - UICollectionViewDelegateFlowLayout -
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return collectionView.frame.size;
}

#pragma mark - UIScrollViewDelegate -
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self clearTimer];
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    self.pageControl.currentPage = ((int)(scrollView.contentOffset.x / scrollView.frame.size.width) % _count);
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    self.pageControl.currentPage = ((int)(scrollView.contentOffset.x / scrollView.frame.size.width) % _count);
    [self startTimer];
}


@end
